import axios from 'axios';
import store from '@/store';
// import Vue from 'vue';
import { LOGIN_OUT } from '@/store/modules/user';
import { SUCCESS, KASUCCESS, UNAUTHORIZED, OTHERLOGINBYDEVICE, IDEMPOTENT } from '@/constants';
import { NETWORK_ERROR, UNAUTHORIZED_ERROR,OTHERLOGINBYDEVICE_ERROR } from '@/constants/error';
import { Toast } from 'vant';
import { DecryptToken } from '@/utils/auth';
import { User } from '@/utils/cache';
import Router from '../middleware/autoRouter';
import NProgress from 'nprogress';

const JSON_HEADER = 'application/json;charset=UTF-8';
const FILE_HEADER = 'multipart/form-data';

let IS_FILE = false;

axios.defaults.withCredentials = false;
const request = axios.create({
  timeout: 15000 // 请求超时时间
});

const noop = (v) => {
  return v;
};

let setCustomHeader = noop;

let LogingToast = null;
// request拦截器

request
  .interceptors
  .request
  .use(config => {
    NProgress.start();
    // loading.open();

    Toast.clear();

    LogingToast ? LogingToast.clear() : LogingToast = null;

    LogingToast = Toast.loading({ message: '加载中...', forbidClick: true, loadingType: 'spinner', duration: 0 });
    if (store.getters.getUserInfo.accessToken) {
      config.headers['AccessToken'] = store.getters.getUserInfo.accessToken; // 增加AccessToken
    }
    config.headers['fromApp'] = 'pc-kah5-v1'; // H5端请求标识
    config.headers['realFromApp'] = 'h5-ka-bd-v1'; // H5端请求标识
    config.headers['Content-Type'] = IS_FILE ? FILE_HEADER : JSON_HEADER;

    // const curTab = store.getters.getTabs[store.getters.getCurrentTab];
    // config.headers['menuid'] = curTab.menuid
    config.headers['pragma'] = 'no-cache';
    return setCustomHeader(config);
  }, error => {
    NProgress.done();
    // loading.close();
    LogingToast.clear();
    Promise.reject(error);
  });

// respone拦截器
request
  .interceptors
  .response
  .use(response => {
    NProgress.done();
    // loading.close();
    LogingToast.clear();
    const res = response.data;
    // 如果http header 中 refresh-token 字段不为空，则刷新token及用户信息
    const refreshToken = response.headers['refresh-token'];

    if (refreshToken) {
      const userInfo = DecryptToken.getUserInfo(refreshToken);

      userInfo.accessToken = refreshToken;
      User.setUserInfo(userInfo);
      store.commit('SET_USERINFO', userInfo);
    }
    if (res) {
      if (res.code == IDEMPOTENT) {
        return false;
      }
      if (res.code == SUCCESS || res.code == KASUCCESS) {
        return res;
      }
      // token失效或验证失败
      if (res.code == UNAUTHORIZED) {
        Toast.fail({
          message: UNAUTHORIZED_ERROR, onClose: function () {
            store.dispatch(LOGIN_OUT).then(() => {
              Router.push('/login');
            });
          }
        });
      } else if(res.code == OTHERLOGINBYDEVICE){ // OTHERLOGINBYDEVICE => 408
        Toast.fail({
          message: OTHERLOGINBYDEVICE_ERROR, onClose: function () {
            store.dispatch(LOGIN_OUT).then(() => {
              Router.push('/login');
            });
          }
        });
      }
      else if (res.type == 'multipart/form-data') { // 判断是否是导出数据
        return response;
      } else if (res.code == 3003) { // 判断是否是导出数据
        return res;
      } else {
        Toast.fail(res.message);
        return Promise.reject('');
      }

    } else {
      Toast.fail(NETWORK_ERROR);
      return Promise.reject('');
    }
    return {};
  }, error => {
    console.log(error);
    NProgress.done();
    // loading.close();
    LogingToast.clear();
    const res = error.response;
    console.log(res.code)

    if (res) {
      if (res.status == UNAUTHORIZED) {
        Toast.fail({
          message: UNAUTHORIZED_ERROR, onClose: function () {
            store.dispatch(LOGIN_OUT).then(() => {
              Router.push('/login');
            });
          }
        });
      } else if(res.status == OTHERLOGINBYDEVICE){ // OTHERLOGINBYDEVICE => 408
        Toast.fail({
          message: OTHERLOGINBYDEVICE_ERROR, onClose: function () {
            store.dispatch(LOGIN_OUT).then(() => {
              Router.push('/login');
            });
          }
        });
      } else {
        if (res.data.code == UNAUTHORIZED) {
          Toast.fail({
            message: UNAUTHORIZED_ERROR, onClose: function () {
              store.dispatch(LOGIN_OUT).then(() => {
                Router.push('/login');
              });
            }
          });
        } else if(res.code == OTHERLOGINBYDEVICE){ // OTHERLOGINBYDEVICE => 408
          Toast.fail({
            message: OTHERLOGINBYDEVICE_ERROR, onClose: function () {
              store.dispatch(LOGIN_OUT).then(() => {
                Router.push('/login');
              });
            }
          });
        } else {
          Toast.fail(res.data.message);
          return Promise.reject('');
        }
      }

      return {};
    } else {
      Toast.fail(NETWORK_ERROR);
      return Promise.reject('');
    }
  });
export const post = function (ops) {
  IS_FILE = false;
  const { setHeader } = ops;

  setCustomHeader = setHeader ? setHeader() : noop;

  return request({
    method: 'post',
    ...ops
  });
};
export const get = function (ops) {
  IS_FILE = false;
  const { setHeader } = ops;

  setCustomHeader = setHeader ? setHeader() : noop;

  return request({
    method: 'get',
    ...ops
  });
};
export const upload = function (ops) {
  IS_FILE = true;
  const { setHeader } = ops;

  setCustomHeader = setHeader ? setHeader() : noop;

  return request({
    method: 'post',
    ...ops
  });
};

export default request;
